import store from '../store/index';
import {ElMessage} from "element-plus";
import Cookie from "js-cookie";

var websocket = {
    webSocket: null,
    url: '',
    keeplive: 1000,//心跳间隔 毫秒
    scene: ['link', 'notify', 'file', 'login', 'system', 'pong'],//notify,file,login,system
    noNeedHandleScene: ['link', 'pong'],
    keepliveFunc: null,
    allowReconnect: true,
    reconnectFunc: null,
    reconnectCurrentNum: 0,
    allowReconnectNum: 3,
    reconnectInterval: 1000,
    isAuthority: false,//是否以身份认证
    messageCallback: null,
    openCallback: null,
    closeCallback: null,
    errorCallback: null,
    /**
     * 0 (WebSocket.CONNECTING) 正在链接中
     * 1 (WebSocket.OPEN) 已经链接并且可以通讯
     * 2 (WebSocket.CLOSING) 连接正在关闭
     * 3 (WebSocket.CLOSED) 连接已关闭或者没有链接成功
     */
    readyState: 0,
    init: (url) => {
        if (!("WebSocket" in window)) {
            ElMessage.error('浏览器不支持WebSocket，请使用chrome浏览器');
            return null
        }

        if (websocket.webSocket) {
            return websocket.webSocket
        }
        if (websocket.url == '') {
            websocket.url = url;
        }

        websocket.webSocket = new WebSocket(websocket.url);

        websocket.webSocket.onmessage = websocket.messageCallback
            ? websocket.messageCallback(e)
            : websocket.webSocket.onmessage = function (e) {
                websocket.message(e);
            }

        websocket.webSocket.onopen = websocket.openCallback
            ? websocket.openCallback(e)
            : function (e) {
                websocket.readyState = 1
                // 开启心跳
                websocket.keepAlive()
            }

        websocket.webSocket.onclose = websocket.closeCallback
                ? websocket.closeCallback(e)
                : function (e) {
                    clearInterval(websocket.keepliveFunc)
                    websocket.readyState = websocket.webSocket.CLOSED;

                    // 需要重新连接
                    if (websocket.allowReconnect) {
                        websocket.reconnectFunc = setTimeout(() => {
                            // 超过重连次数
                            if (websocket.reconnectCurrentNum > websocket.allowReconnectNum) {
                                clearTimeout(websocket.reconnectFunc)
                                return
                            }

                            // 记录重连次数
                            websocket.reconnectCurrentNum++
                            websocket.reconnect()
                        }, websocket.reconnectInterval)
                    }
                }

        websocket.webSocket.onerror = function (e) {
            ElMessage.error('系统异常，链接已断开，请关闭页面重试');
            console.log(e);
        }
    },

    message: (e) => {
        var message = JSON.parse(e.data);
        let data = message.data,
            msg = message.message,
            code = message.code,
            scene = message.scene;

        if (websocket.noNeedHandleScene.indexOf(scene) > -1) {
            if (code == 1) {
                if (msg != '') {
                    ElMessage.success({
                        message: msg,
                        type: 'success',
                    });
                }
            } else {
                ElMessage.error(msg);
            }
        } else {
            websocket[scene](code, msg, data);
        }
    },
    close: (e) => {
        clearInterval(websocket.keepliveFunc)
        websocket.readyState = websocket.webSocket.CLOSED;
        websocket.webSocket.close()
    },
    error: (e) => {
    },
    login(code, msg, data) {
        if (code == 1) {
            websocket.isAuthority = true;
            ElMessage.success({
                message: msg,
                type: 'success'
            })
        } else {
            ElMessage.error(msg);
        }
    },
    send: (data, callback = null) => {
        try {
            if (websocket.webSocket.readyState === websocket.webSocket.OPEN) {
                let res = websocket.webSocket.send(JSON.stringify(data));
                if (callback) {
                    return callback();
                }
            } else if (websocket.webSocket.readyState === websocket.webSocket.CONNECTING) {
                setTimeout(function () {
                    websocket.send(data, callback)
                }, 1000)

                // 未开启，则等待1s后重新调用
            } else {
                if (websocket.allowReconnect) {
                    websocket.init()
                    setTimeout(function () {
                        websocket.send(data, callback)
                    }, 1000)
                }
            }
            return;
        } catch (e) {
            console.log(e.message);
        }

    },
    reconnect: () => {
        if (websocket.allowReconnect) {
            websocket.init()
        }
    },
    connect: () => {
        let data = {},
            uuid = store.getters.getUUid,
            sid = store.getters.getSid,
            token = store.getters.getToken,
            rid = Cookie.get('rid');

        if ((!token && !rid) || !uuid || !sid) {
            ElMessage.error('缺少设备信息主动断开')
            websocket.close();
        }

        data = {
            uuid: uuid,
            sid: sid,
            token: token,
            rid: rid
        };

        var params = {
            scene: 'login',
            data: data
        }
        websocket.send(params)
    },
    keepAlive: () => {
        if (!websocket.isAuthority) {
            websocket.connect();
        }
        if (websocket.keepliveFunc) {
            clearInterval(websocket.keepliveFunc)
        }

        try {
            websocket.keepliveFunc = setInterval(() => {
                websocket.send({scene: 'ping'})
            }, websocket.keeplive)

        } catch (e) {
            console.log(e.message)
        }

    }
}
export default websocket;